JS30官網
今天來講解第十六天吧!這天會學到mousemvoe這個事件以及offset的用法
我們的目標是要讓h1這個字體的textshadow可以跟著滑鼠移動,並且中心點在h1這個字體上
我們先來看html
div class="hero">
    <h1 contenteditable>?太神拉</h1>
  </div>
  <style>
  html {
    color: black;
    font-family: sans-serif;
  }
  body {
    margin: 0;
  }
  .hero {
    min-height: 100vh;
    display: flex;
    justify-content: center;
    align-items: center;
    color: black;
  }
  h1 {
    text-shadow: 10px 10px 0 rgba(0,0,0,1);
    font-size: 100px;
  }
  </style>
老樣子先選擇到需要的元素
  const hero = document.querySelector('.hero');
  const text = hero.querySelector('h1');
選取到最外層的div以及h1本身,並且我們要在最外層的區塊監聽mousemove事件,而mousemove這個事件,是指要滑鼠移動的時候都會監聽!
  hero.addEventListener('mousemove', shadow);
function shadow(e) {
    const hash = { w: hero.offsetWidth, h: hero.offsetHeight };
    let move = { x: e.offsetX, y: e.offsetY };
    if (this !== e.target) {
      move.x = move.x + e.target.offsetLeft;
      move.y = move.y + e.target.offsetTop;
    }
    const xWalk = Math.round((move.x / hash.w * walk) - (walk / 2));
    const yWalk = Math.round((move.y / hash.h * walk) - (walk / 2));
    text.style.textShadow = `
      ${xWalk}px ${yWalk}px 0 rgba(255,0,255,0.7),
      ${xWalk * -1}px ${yWalk}px 0 rgba(0,255,255,0.7),
      ${yWalk}px ${xWalk * -1}px 0 rgba(0,255,0,0.7),
      ${yWalk * -1}px ${xWalk}px 0 rgba(0,0,255,0.7)
    `;
  }
我們一個一個來看,我們想要先選擇到最外層div的offsetWidth以及offsetHeight,也就是這個元素實際的寬與高!
那e就是這個事件,在裡面可以看到有offsetX、offsetY其實就是指滑鼠到外層容器的距離!
    if (this !== e.target) {
      move.x = move.x + e.target.offsetLeft;
      move.y = move.y + e.target.offsetTop;
    }
都選擇到了之後我們要去判斷現在滑鼠是不是在hero這個外層div上,如果不是的話就會是在h1上,那麼我們要加上h1的offsetLeft、offsetTop才會是正確的值,否則滑到h1的時候會有問題。那this就是指綁定監聽事件的元素,也就是hero,e.target就是去判斷目前滑鼠指在哪一個元素上。
    const xWalk = Math.round((move.x / hash.w * walk) - (walk / 2));
    const yWalk = Math.round((move.y / hash.h * walk) - (walk / 2));
主要是讓原本圓點在左上角,改成在h1上才是中心點
    text.style.textShadow = `
      ${xWalk}px ${yWalk}px 0 rgba(255,0,255,0.7),
      ${xWalk * -1}px ${yWalk}px 0 rgba(0,255,255,0.7),
      ${yWalk}px ${xWalk * -1}px 0 rgba(0,255,0,0.7),
      ${yWalk * -1}px ${xWalk}px 0 rgba(0,0,255,0.7)
    `;
最後新增textShadow的CSS樣式,完成!
今天就講解到這邊,謝謝大家,明天見!